package com.pubinfo.passbook.common.service.dubbo.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.pubinfo.passbook.common.exception.ServiceException;
import com.pubinfo.passbook.common.mapper.TSubsidiaryInfoMapper;
import com.pubinfo.passbook.common.model.bo.eip.ReceiveTaskParam;
import com.pubinfo.passbook.common.model.bo.eip.ReceiveTaskResult;
import com.pubinfo.passbook.common.model.bo.uccp.ShortMessageParam;
import com.pubinfo.passbook.common.model.bo.witeoff.CityInfo;
import com.pubinfo.passbook.common.model.constant.RedisKey;
import com.pubinfo.passbook.common.model.dubbo.ESBServiceData;
import com.pubinfo.passbook.common.model.shortMessage.QueryMessageBodyParam;
import com.pubinfo.passbook.common.model.shortMessage.QueryMessageReply;
import com.pubinfo.passbook.common.model.shortMessage.ShortMessageBodyReply;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.service.cache.JedisManage;
import com.pubinfo.passbook.common.service.dubbo.DubboService;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@SuppressWarnings("ALL")
@Service
public class DubboServiceImpl implements DubboService {
  @Value("${post.url}")
  String postUrl;
  
  @Autowired
  TSubsidiaryInfoMapper infoMapper;
  @Resource
  JedisManage jedisManage;
  @Value("${post.dubbo-port}")
  String dubboPort;
  
  @Override
  public String getPersonsDetailByStatus(String idNo) {
    
    return getPersonsDetailByIdNo(idNo).getStaffStatus();

  }
  
  @Override
  public String getUserNsrsbhByAcct(String acct) {
    
    ESBServiceData.CertDetail certDetail = getPersonsDetailByIdNo(acct);
    if (certDetail == null) {
      throw new ServiceException("该账号在人力系统不存在！请找系统管理员咨询");
    }

    //公司名称
    String areaName = certDetail.getCountyName();
    
    CityInfo info = infoMapper.findCityInfoByNsrsbh(areaName);
    return info.getNsrsbh();
  }
  
  @Override
  public ESBServiceData.CertDetail getPersonsDetailByIdNo(String idNo) {
    String reply = jedisManage.getStr(RedisKey.USER_NO_ID + idNo);
    if (StringUtils.isBlank(reply)) {
      reply = getPersonsDetailByAcct(new ESBServiceData.Cert(idNo), 1);
  
    }
    JsonResult<Collection<ESBServiceData.CertDetail>> jsonResult = JSONObject.toJavaObject(JSON.parseObject(reply), JsonResult.class);
    if (!CollectionUtils.isEmpty(jsonResult.getResult())) {
      Collection<ESBServiceData.CertDetail> certDetails = jsonResult.getResult();
      List<ESBServiceData.CertDetail> cartItems =
          JSONArray.parseArray(JSON.toJSONString(certDetails), ESBServiceData.CertDetail.class);
      jedisManage.putStr(RedisKey.USER_NO_ID + idNo, reply);
      return cartItems.get(0);
    }
    return null;
  }
  
  @Override
  public String getPersonsDetailByAcct(String idNo) {
    ESBServiceData.CertDetail certDetail = getPersonsDetailByIdNo(idNo);
    return certDetail != null ? certDetail.getStaffCode() : null;
  }
  
  @SneakyThrows
  public String getPersonsDetailByAcct(ESBServiceData.Cert cert, Integer count) {
    String reply = sendDubboPost(JSONObject.toJSONString(cert), "/api/esb/get");
    JsonResult<Collection<ESBServiceData.CertDetail>> jsonResult = JSONObject.toJavaObject(JSON.parseObject(reply), JsonResult.class);
    if (count < 3 && jsonResult.getStatus() == 500) {
      Thread.sleep(1500L);
      getPersonsDetailByAcct(cert, count++);
    }
    return reply;
  }
  
  private String sendDubboPost(String s, String url) {
    
    return sendPost(s, postUrl + ":" + dubboPort + url);
  }
  
  @Override
  public JsonResult<Collection<ESBServiceData.CertDetail>> getPersonsDetailByAcct(ESBServiceData.Cert cert) {
    
    String reply = sendDubboPost(JSONObject.toJSONString(cert), "/api/esb/get");
    
    return JSONObject.toJavaObject(JSON.parseObject(reply), JsonResult.class);
  }
  
  private String sendPost(String s, String url) {
    //Unirest.setTimeouts(0, 0);
    HttpResponse<String> response = null;
    try {
      response = Unirest.post(url)
          .header("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)")
          .header("Content-Type", "application/json")
          .header("Accept-Encoding", "gzip, deflate, br")
          .body(s)
          .asString();
    } catch (UnirestException e) {
      throw new ServiceException("调用服务失败", e);
    }
    return response.getBody();
  }
  
  @Override
  public Boolean sendShortMessage(ShortMessageParam param) {
//    param.setAccNbr("18667018123");
    String reply = sendDubboPost(JSONObject.toJSONString(param), "/api/uccp/sendShortMessage");
    ShortMessageBodyReply bodyReply = JSONObject.toJavaObject(JSON.parseObject(reply), ShortMessageBodyReply.class);
    if ("0000".equals(bodyReply.getCode().trim())) {
      //成功后逻辑
      return true;
    }
    JSONObject.parseObject(reply);
    return false;
  }
  
  @Override
  public QueryMessageReply queryMessage(QueryMessageBodyParam param) {
    String reply = sendDubboPost(JSONObject.toJSONString(param), "/api/uccp/queryMessage");
    QueryMessageReply bodyReply = JSONObject.toJavaObject(JSON.parseObject(reply), QueryMessageReply.class);
    return bodyReply;
  }
  
  @Override
  public ReceiveTaskResult receiveTaskInfo(ReceiveTaskParam taskParam) {
    List<ReceiveTaskParam> taskParams = new ArrayList<>();
    taskParams.add(taskParam);
    String reply = sendDubboPost(JSONObject.toJSONString(taskParams), "/api/eip/receiveTaskInfo");
    ReceiveTaskResult bodyReply = JSONObject.toJavaObject(JSON.parseObject(reply), ReceiveTaskResult.class);
    return bodyReply;
  }
  
  @Override
  public ReceiveTaskResult  finishedTask(String taskId) {
    String reply = sendDubboPost(taskId, "/api/eip/finishedTask");
    ReceiveTaskResult bodyReply = JSONObject.toJavaObject(JSON.parseObject(reply), ReceiveTaskResult.class);
    return bodyReply;
  }
}
